package com.ruoyi.documents.controller;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.documents.domain.DocXmjl;
import com.ruoyi.documents.dto.DocProjectDto;
import com.ruoyi.documents.service.IDocXmjlService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.documents.domain.DocProject;
import com.ruoyi.documents.service.IDocProjectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目信息Controller
 * 
 * @author ruoyi
 * @date 2023-12-18
 */
@RestController
@RequestMapping("/documents/project")
public class DocProjectController extends BaseController
{
    @Autowired
    private IDocProjectService docProjectService;

    @Autowired
    private IDocXmjlService docXmjlService;

    /**
     * 查询项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('documents:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(DocProject docProject)
    {
        startPage();
        List<DocProject> list = docProjectService.selectDocProjectList(docProject);
        return getDataTable(list);
    }

    /**
     * 导出项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('documents:project:export')")
    @Log(title = "项目信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DocProject docProject)
    {
        List<DocProject> list = docProjectService.selectDocProjectList(docProject);
        ExcelUtil<DocProject> util = new ExcelUtil<DocProject>(DocProject.class);
        util.exportExcel(response, list, "项目信息数据");
    }

    /**
     * 获取项目信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('documents:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(docProjectService.selectDocProjectById(id));
    }

    /**
     * 新增项目信息
     */
    @PreAuthorize("@ss.hasPermi('documents:project:add')")
    @Log(title = "项目信息", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody DocProject docProject)
    {
        // 新增已完工项目 无需判断
        if (docProject.getStatus().equals(DocProject.Finished)) {
            return toAjax(docProjectService.insertDocProject(docProject));
        }else if (docProject.getStatus().equals(DocProject.noFinish)) {
            // 新增未完工项目
            Long xmjlId = docProject.getXmjlId();
            // 新建项目时绑定 项目经理
            if (xmjlId != null) {
                DocXmjl docXmjl = docXmjlService.selectDocXmjlByXmjlId(xmjlId);
                // 未查询到该项目经理
                if (docXmjl == null) {
                    return error("为查询到该项目经理，请刷新页面后重新选择！");
                }
                // 该项目经理 有未完成项目
                if (docXmjl.getStatus().equals(DocXmjl.noFinish)) {
                    return error("项目经理编号：" + docXmjl.getXmjlId() + "，" + "项目经理名称：" + docXmjl.getXmjlName() + "，"
                            + "正在进行" + "项目编号:" + docXmjl.getProjectId() + "，" + "项目名称：" + docXmjl.getProjectName()
                            + "的任务，请先结束该任务！");
                }
                // 修改项目经理表
                DocXmjl docXmjl1 = new DocXmjl();
                docXmjl1.setXmjlId(xmjlId);
                docXmjl1.setStatus(DocXmjl.noFinish);
                docXmjl1.setProjectName(docProject.getName());
                // 修改项目表
                docProject.setDeptId(getDeptId());
                docProject.setUserId(getUserId());
                int proi = docProjectService.insertDocProject(docProject);
                docXmjl1.setProjectId(docProject.getId());
                // 执行修改操作
                int xmjli = docXmjlService.updateDocXmjl(docXmjl1);
                // 执行插入操作
                // 释放锁
                return toAjax(xmjli + proi);
            }
            else {
                // 不绑定项目经理
                // 修改项目表
                docProject.setDeptId(getDeptId());
                docProject.setUserId(getUserId());
                return toAjax(docProjectService.insertDocProject(docProject));
            }
        }
        return null;
    }

    /**
     * 修改项目信息
     */
    @PreAuthorize("@ss.hasPermi('documents:project:edit')")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody DocProjectDto docProject)
    {
        // 更新 旧项目经理状态
        DocXmjl docXmjl1 = new DocXmjl();
        docXmjl1.setXmjlId(docProject.getOldXmjlId());
        docXmjl1.setStatus(DocXmjl.Finished);
        int xnjli1 = docXmjlService.updateDocXmjl(docXmjl1);

        // 更新 新项目经理状态
        DocXmjl docXmjl = new DocXmjl();
        docXmjl.setXmjlId(docProject.getXmjlId());
        docXmjl.setProjectId(docProject.getId());
        docXmjl.setProjectName(docProject.getName());
        docXmjl.setStatus(docProject.getStatus());
        int xnjli = docXmjlService.updateDocXmjl(docXmjl);

        // 更新 项目状态
        int proi = docProjectService.updateDocProject(docProject);
        // 更新成功
        if (xnjli > 0 && proi > 0 && xnjli1 > 0) {
            return toAjax(xnjli + proi + xnjli1);
        }
        // 更新失败
        return toAjax(-1);
    }


    /**
     * 删除项目信息
     */
    @PreAuthorize("@ss.hasPermi('documents:project:remove')")
    @Log(title = "项目信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}/{xmjlids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids, @PathVariable Long[] xmjlids)
    {
        // 修改项目经理状态
        for (Long id : xmjlids) {
            DocXmjl docXmjl = new DocXmjl();
            docXmjl.setXmjlId(id);
            docXmjl.setStatus(DocXmjl.Finished);
            int xmjli = docXmjlService.updateDocXmjl(docXmjl);
            if (xmjli <= 0) {
                return toAjax(xmjli);
            }
        }
        return toAjax(docProjectService.deleteDocProjectByIds(ids));
    }

}
